import {
    HomeOutlined,
    ReadOutlined,
    AppstoreOutlined,
    ProfileOutlined,
    FileAddOutlined,
    FileTextOutlined,
    UserOutlined,
    SolutionOutlined,
    PictureOutlined,
    KeyOutlined
  } from '@ant-design/icons';
import type { FC } from "react";
import type { MenuProps } from 'antd';
import { Menu,} from 'antd';
import { useLoaderData ,useLocation,useNavigate} from "react-router-dom";

const iconMap = {
    //键：值
    //icon名字：替换成图标组件
    HomeOutlined:<HomeOutlined/>,
    ReadOutlined:<ReadOutlined/>,
    AppstoreOutled:<AppstoreOutlined/>,
    ProfileOutlined:<ProfileOutlined/>,
    FileAddOutlined:<FileAddOutlined/>,
    FileTextOutlined:<FileTextOutlined/>,
    UserOutlined:<UserOutlined/>,
    SolutionOutlined:<SolutionOutlined/>,
    PictureOutlined:<PictureOutlined/>,
    KeyOutlined:<KeyOutlined/>
} 

const RootMenu:FC = () =>{
    const data = useLoaderData() as {menus:MenuItem[]} |null
    //函数式组件中不能按条件执行hook，必须在顶部调用
    const navigate =useNavigate()
    //默认被选中菜单项的key,同时处理索引路由无法被选中的问题
    const location = useLocation()
    const selectKey = location.pathname ==='/'? '/home':location.pathname
    if(!data) return
    const {menus} = data
    //递归处理图标
    resolveMenuIcon(menus)

    const onManuItemClick:MenuProps['onClick'] =({key})=>{
        //路由跳转
        console.log(key);
        navigate(key)
    }
    return (<>
      <Menu
          theme="dark"
          mode="inline"
          items={menus}
          onClick={onManuItemClick}
          selectedKeys={[selectKey]}
        />
    </>)
}




//递归处理每个菜单项的图标
const resolveMenuIcon =(menus:MenuItem[])=>{
    for(const menu of menus){
        const iconName = menu.icon as keyof typeof iconMap
        menu.icon = iconMap[iconName]
        if(menu.children){
            resolveMenuIcon(menu.children)
        }
    }
}

//

export default RootMenu
